//
//  PKRequestManager.m
//  PianKe
//
//  Created by lanou on 15/12/22.
//  Copyright © 2015年 KFC. All rights reserved.
//

#import "PKRequestManager.h"

@implementation PKRequestManager


+ (void)requestWithUrlString:(NSString *)urlString
                      parDic:(NSDictionary *)parDic
                      Method:(RequestType)method
                      finish:(Finish)finish
                      error:(Error)error
                      path:(NSString *)path
{
    
    // 网址对象:
    NSURL *url = [[NSURL alloc] initWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    // 网址请求:
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 判断请求的方式
    if (method == POST) {
        [request setHTTPMethod:@"POST"];
        if (parDic.count != 0) {
            // 说明有参数
            NSMutableArray *strArray = [NSMutableArray array];
            for (NSString *key in parDic) {
                
                NSString *str = [NSString stringWithFormat:@"%@=%@",key,parDic[key]];
                [strArray addObject:str];
            }
            // 然后拼接数组
            // componentsJoinedByString这个方法是自动把数组里面的每一个元素用@" "里的符号连接起来
           NSString *parString =  [strArray componentsJoinedByString:@"&"];
            // 设置请求体
            [request setHTTPBody:[parString dataUsingEncoding:NSUTF8StringEncoding]];
            
            
        }
    }
    
    // 如果是GET,直接走这步
    
    // 获取data
    [NSURLConnection sendAsynchronousRequest:request queue:( [NSOperationQueue mainQueue]) completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        
        // 缓存设置
        NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
//        NSLog(@"%@",cachePath);
        NSString *savePath = [cachePath stringByAppendingPathComponent:path];
        
        if (connectionError == nil) {
//            NSLog(@"请求成功");
            
            // 带本地化的处理:
            
            // 存入本地
            [NSKeyedArchiver archiveRootObject:data toFile:savePath];
            // 通过block传值data
            finish(data);  // 函数的调用
        } else {
//            NSLog(@"请求失败");
            // 通过block传值错误信息
            error(connectionError); // 函数的地调用
            
            // 读取本地的上一次缓存文件
            NSData *pickData = [NSKeyedUnarchiver unarchiveObjectWithFile:savePath];
            if (pickData != nil && ![pickData isKindOfClass:[NSNull class]]){
                finish(pickData);
            }
            
            
        }
        
    }];
    

    
    
}


@end
